package com.byealen;

import com.byealen.util.JrebelSign;
import com.byealen.entity.R;
import com.byealen.entity.Result;
import com.byealen.util.Rsasign;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@org.springframework.stereotype.Controller
public class Controller {

    @PostMapping(value = "info")
    @ResponseBody
    public R<Map> web(HttpServletRequest request) {
        String basePath = request.getScheme() + "://" + request.getServerName();
        if (request.getServerPort() != 80) {
            basePath += ":" + request.getServerPort();
        }
        HashMap<Object, Object> map = new HashMap<>(2);
        map.put("url", basePath);
        map.put("key", UUID.randomUUID().toString());
        return R.data(map);
    }

    @ResponseBody
    @RequestMapping(value = {"/jrebel/leases", "/agent/leases"})
    public Result jrebelLeasesHandler(
            HttpServletResponse response,
            @RequestParam("randomness") String clientRandomness, @RequestParam(value = "username", required = false) String username,
            @RequestParam("guid") String guid, @RequestParam(value = "offline", required = false) boolean offline,
            @RequestParam("clientTime") Long clientTime) {
        response.setContentType("application/json; charset=utf-8");
        response.setStatus(HttpServletResponse.SC_OK);
        Long validFrom = null;
        Long validUntil = null;
        if (offline & clientTime != null) {
            long clinetTimeUntil = clientTime + 180L * 24 * 60 * 60 * 1000;
            validFrom = clientTime;
            validUntil = clinetTimeUntil;
        }

        Result result = new Result();
        result.setServerVersion("3.2.4");
        result.setServerProtocolVersion("1.1");
        result.setServerGuid("a1b4aea8-b031-4302-b602-670a990272cb");
        result.setGroupType("managed");
        result.setId(1);
        result.setLicenseType(1);
        result.setEvaluationLicense(false);
        result.setSignature("OJE9wGg2xncSb+VgnYT+9HGCFaLOk28tneMFhCbpVMKoC/Iq4LuaDKPirBjG4o394/UjCDGgTBpIrzcXNPdVxVr8PnQzpy7ZSToGO8wv/KIWZT9/ba7bDbA8/RZ4B37YkCeXhjaixpmoyz/CIZMnei4q7oWR7DYUOlOcEWDQhiY=");
        result.setServerRandomness("H2ulzLlh7E0=");
        result.setSeatPoolType("standalone");
        result.setStatusCode("SUCCESS");
        result.setOffline(offline);
        result.setValidFrom(validFrom);
        result.setValidUntil(validUntil);
        result.setCompany("Administrator");
        result.setOrderId("");
        result.setZeroIds(new ArrayList<>());
        result.setLicenseValidFrom(1490544001000L);
        result.setLicenseValidUntil(1691839999000L);

        if (clientRandomness == null || username == null || guid == null) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        } else {
            JrebelSign jrebelSign = new JrebelSign();
            jrebelSign.toLeaseCreateJson(clientRandomness, guid, offline, validFrom, validUntil);
            String signature = jrebelSign.getSignature();
            result.setSignature(signature);
            result.setCompany(username);
            return result;
        }
        return null;
    }

    @ResponseBody
    @RequestMapping(value = {"/jrebel/leases/1", "/agent/leases/1"})
    public Result jrebelLeases1Handler(HttpServletResponse response, @RequestParam("username") String username) {
        response.setContentType("application/json; charset=utf-8");
        response.setStatus(HttpServletResponse.SC_OK);
        Result result = new Result();
        result.setServerVersion("3.2.4");
        result.setServerProtocolVersion("1.1");
        result.setServerGuid("a1b4aea8-b031-4302-b602-670a990272cb");
        result.setGroupType("managed");
        result.setStatusCode("SUCCESS");
        result.setMsg(null);
        result.setStatusMessage(null);
        if (username != null) {
            result.setCompany(username);
        }
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/jrebel/validate-connection")
    public Result jrebelValidateHandler(HttpServletResponse response, @RequestParam("username") String username) {
        response.setContentType("application/json; charset=utf-8");
        response.setStatus(HttpServletResponse.SC_OK);
        Result result = new Result();
        result.setServerVersion("3.2.4");
        result.setServerProtocolVersion("1.1");
        result.setServerGuid("a1b4aea8-b031-4302-b602-670a990272cb");
        result.setGroupType("managed");
        result.setStatusCode("SUCCESS");
        result.setCompany(username);
        result.setCanGetLease(true);
        result.setLicenseType(1);
        result.setEvaluationLicense(false);
        result.setSeatPoolType("standalone");

        return result;
    }

    @RequestMapping(value = "/rpc/ping.action")
    public void pingHandler(HttpServletResponse response, @RequestParam("salt") String salt) throws IOException {
        response.setContentType("text/html; charset=utf-8");
        response.setStatus(HttpServletResponse.SC_OK);
        if (salt == null) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        } else {
            String xmlContent = "<PingResponse><message></message><responseCode>OK</responseCode><salt>" + salt + "</salt></PingResponse>";
            String xmlSignature = Rsasign.Sign(xmlContent);
            String body = "<!-- " + xmlSignature + " -->" + xmlContent;
            response.getWriter().print(body);
        }
    }

    @RequestMapping(value = "/rpc/obtainTicket.action")
    public void obtainTicketHandler(HttpServletResponse response,
                                    @RequestParam("salt") String salt,
                                    @RequestParam("userName") String username) throws IOException {
        response.setContentType("text/html; charset=utf-8");
        response.setStatus(HttpServletResponse.SC_OK);
        SimpleDateFormat fm = new SimpleDateFormat("EEE,d MMM yyyy hh:mm:ss Z", Locale.ENGLISH);
        String date = fm.format(new Date()) + " GMT";
        //response.setHeader("Date", date);
        //response.setHeader("Server", "fasthttp");
        String prolongationPeriod = "607875500";
        if (salt == null || username == null) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        } else {
            String xmlContent = "<ObtainTicketResponse><message></message><prolongationPeriod>" + prolongationPeriod + "</prolongationPeriod><responseCode>OK</responseCode><salt>" + salt + "</salt><ticketId>1</ticketId><ticketProperties>licensee=" + username + "\tlicenseType=0\t</ticketProperties></ObtainTicketResponse>";
            String xmlSignature = Rsasign.Sign(xmlContent);
            String body = "<!-- " + xmlSignature + " -->" + xmlContent;
            response.getWriter().print(body);
        }
    }

    @RequestMapping(value = "/rpc/releaseTicket.action")
    public void releaseTicketHandler(HttpServletResponse response, @RequestParam("salt") String salt) throws IOException {
        response.setContentType("text/html; charset=utf-8");
        response.setStatus(HttpServletResponse.SC_OK);
        if (salt == null) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        } else {
            String xmlContent = "<ReleaseTicketResponse><message></message><responseCode>OK</responseCode><salt>" + salt + "</salt></ReleaseTicketResponse>";
            String xmlSignature = Rsasign.Sign(xmlContent);
            String body = "<!-- " + xmlSignature + " -->" + xmlContent;
            response.getWriter().print(body);
        }
    }
}
